package com.cbh.amadeus.server.handler;

import com.cbh.amadeus.common.enums.MessageType;
import com.cbh.amadeus.common.protocol.AmadeusMessage;
import com.cbh.amadeus.common.protocol.AmadeusMessageProtocol;
import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import com.cbh.amadeus.server.utils.TopicChannelManage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/5/22
 */
@Slf4j
public class OnlyConnectSendHandler extends SimpleChannelInboundHandler<AmadeusMessageWrap> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AmadeusMessageWrap msg) {
        MessageType type = MessageType.find(msg.getType());
        if (type == MessageType.ONLY_CONNECT_SEND) {
            log.info(
                    "===== [ONLY CONNECT] Request from the [{} - {}] =====",
                    ctx.channel().remoteAddress(),
                    TopicChannelManage.origin(msg.getMessage().getProvider())
            );
            ctx.writeAndFlush(onlyConnectBack(msg));
            return;
        }
        ctx.fireChannelRead(msg);
    }

    private AmadeusMessageWrap onlyConnectBack(AmadeusMessageWrap msg) {
        AmadeusMessageWrap wrap = new AmadeusMessageWrap();
        wrap.setMagic(AmadeusMessageProtocol.MAGIC);
        wrap.setType((MessageType.ONLY_CONNECT_BACK.getType().byteValue()));
        wrap.setMessage(
                new AmadeusMessage()
                        .setProvider(msg.getMessage().getProvider())
        );
        return wrap;
    }
}
